package org.jks.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.jks.model.User;
import org.springframework.stereotype.Repository;

@Repository("UserServiceImpl")
public class UserServiceImpl extends BaseDaoImpl<User>{
	
	public void save(List<User> users){
		Session session = this.openSession();
		session.beginTransaction();
		for(User user : users){
			session.save(user);
		}
		session.getTransaction().commit();
		session.flush();
		session.close();
	}
	
	public void update(List<User> users){
		Session session = this.openSession();
		for(User user : users){
			session.update(user);
		}
		session.flush();
		session.close();
	}
	
	public List<User> all() {
		return find("from User");
	}

	public void delete(long id) {
		Session session = this.openSession();
		session.delete(session.load(User.class, id));
		session.flush();
		session.close();
	}

	public void delete(long[] ids) {
		Session session = this.openSession();
		StringBuilder strIds = new StringBuilder();
		strIds.append('(');
		int imax = ids.length-1;
        for (int i = 0; ; i++) {
        	strIds.append(ids[i]);
        	if(i == imax){
        		strIds.append(')');
        		break;
        	}
        	strIds.append(", ");
        }
		SQLQuery sqlQuery = session.createSQLQuery("delete from user where id in " + strIds);
		sqlQuery.executeUpdate();
		session.flush();
		session.close();
	}
	
	public User findByName(String name){
		List<Object> param = new ArrayList<Object>();
		param.add(name);
		return get("from User where username=?", param);
	}
	
	public User findByNameAndPwd(String name, String password){
		List<Object> param = new ArrayList<Object>();
		param.add(name);
		param.add(name);
		param.add(password);
		return get("from User where (username=? or email=?) and password=?", param);
	}
}
